package com.rymcu.forest.openai;

import com.rymcu.forest.openai.service.SseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import jakarta.annotation.Resource;

/**
 * Created on 2023/5/26 11:26.
 *
 * @author ronger
 * @email ronger-x@outlook.com
 * @desc : com.rymcu.forest.openai
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/sse")
public class SeeController {

    @Resource
    private SseService sseService;

    @GetMapping(value = "/subscribe/{idUser}", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter subscribe(@PathVariable Long idUser) {
        SseEmitter emitter = sseService.connect(idUser);
        // 设置SSE响应头
        emitter.onCompletion(() -> {
            log.info("SSE连接已完成，用户: {}", idUser);
        });
        return emitter;
    }

    @GetMapping(value = "/close/{idUser}")
    public void close(@PathVariable Long idUser) {
        sseService.close(idUser);
    }

    /**
     * 测试SSE发送
     */
    @GetMapping(value = "/test/{idUser}")
    public String testSse(@PathVariable Long idUser) {
        String testMessage = "这是一条测试消息: " + System.currentTimeMillis();
        boolean sent = sseService.send(idUser, testMessage);
        return sent ? "消息发送成功" : "消息发送失败，用户可能未连接";
    }

}